/**
 *Copyright (c) 2024 watereyes
 * workflow is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.workflow.api.rule;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;

import com.koron.workflow.api.rule.FilterRuleStrategy;
import com.koron.workflow.baseConfig.bean.DepartmentBean;
import com.koron.workflow.baseConfig.mapper.DepartmentMapper;
import com.koron.workflow.common.bean.StaffBean;

/**
 * 只选择上级部门审核人
 * @author bin 
 *
 */
public class FilterRuleStrategy4 implements FilterRuleStrategy{

	@Override
	public List<StaffBean> filter(SessionFactory factory, List<StaffBean> staffs, StaffBean initiator, int autoPicker) {
		DepartmentMapper mapper = factory.getMapper(DepartmentMapper.class);
		DepartmentBean department = mapper.queryForObject(initiator.getDepartmentid());
		List<DepartmentBean> departments = parentDepartments(mapper, new ArrayList<DepartmentBean>(), mapper.queryForObject(department.getParentCode()));
		List<String> ids = departments.stream().map(t -> t.getId()).collect(Collectors.toList());
		staffs = staffs.stream().filter(t -> ids.contains(t.getDepartmentid())).collect(Collectors.toList());
		// 假如自动选人规则为：发起人
		if(autoPicker == 1 && staffs.contains(initiator)) {
			return Arrays.asList(initiator);
		}
		// 假如自动选人规则为：直属上司
		if(autoPicker == 2) {
			return Arrays.asList(initiator);
		}
		return staffs;
	}
	
	private List<DepartmentBean> parentDepartments(DepartmentMapper mapper, List<DepartmentBean> parent, DepartmentBean department){
		if(StringUtils.isEmpty(department.getParentCode()) || StringUtils.equals(department.getId(), department.getParentCode())) {
			return parent;
		}
		parent.add(department);
		DepartmentBean parentDepart = mapper.queryForObject(department.getParentCode());
		return parentDepartments(mapper, parent, parentDepart);
	}

}
